<?php
/**
 * User: hjd-yao
 * Date: 2019/7/23
 * Time: 14:46
 */

namespace Shop\Http\Controllers\Traits;


use App\Models\Shop\OrderGoodsModel;
use App\Models\Shop\OrderModel;
use App\Models\Shop\UserAddressModel;
use Illuminate\Http\Request;

trait OrderTrait
{
    public function delete(Request $request,$order_sn)
    {
        $user_id = $request->input('user_id');
        $order = OrderModel::where('order_sn',$order_sn)->where('uid',$user_id)->first();
        if(!$order){
            return response()->json(['status'=>0,'msg'=>'无该订单信息']);
        }
        if($order->status>0){
            return response()->json(['status'=>0,'msg'=>'该订单正在交易中,不可删除']);
        }

        if(OrderModel::where('order_sn',$order_sn)->where('uid',$user_id)->delete()){
            OrderGoodsModel::where('order_id',$order->order_id)->delete();
            return response()->json(['status'=>1,'msg'=>'删除成功']);
        }
        return response()->json(['status'=>0,'msg'=>'删除失败,请稍后再试']);
    }

    public function cancel(Request $request,$order_sn)
    {
        $user_id = $request->input('user_id');
        $order = OrderModel::where('order_sn',$order_sn)->where('uid',$user_id)->first();
        if(!$order){
            return response()->json(['status'=>0,'msg'=>'无该订单信息']);
        }
        if($order->status>0){
            return response()->json(['status'=>0,'msg'=>'该订单正在交易中,不可删除']);
        }

        if(OrderModel::where('order_sn',$order_sn)->where('uid',$user_id)->delete()){
            OrderGoodsModel::where('order_id',$order->order_id)->delete();
            return response()->json(['status'=>1,'msg'=>'删除成功']);
        }
        return response()->json(['status'=>0,'msg'=>'删除失败,请稍后再试']);
    }

    public function getPostAddr($user_id)
    {
        $address = UserAddressModel::init()->getDefault($user_id);
        if($address){
            $address->address = get_address($address->area).'-'.$address->address;
            $all_address = UserAddressModel::where('user_id',$user_id)->orderBy('updated_at','desc')->limit(5)->get();
            foreach ($all_address as $item){
                $item->address = get_address($item->area).'-'.$item->address;
            }
        }
        view()->share('address',$address);
        view()->share('all_addr',$all_address??'');
    }
}